package com.lovo.ssc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.csc.dto.PurchaseInfoDto;
import com.lovo.psc.dto.OrderDto;
import com.lovo.ssc.entity.BuyPlan;
import com.lovo.ssc.entity.Providorder;
import com.lovo.ssc.service.IBuyPlanService;
import com.lovo.ssc.service.IProvidorderService;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Service
public class ProvideOrderMQService {

    @Autowired
    IProvidorderService service;
    @Autowired
    IBuyPlanService buyPlanService;
    /**
     *这是一个消费者，获取供货单并持久化
     */
    @RabbitListener(queues = "SupplyOrderQueue")
    public void ticket(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, OrderDto dto) throws IOException {
        if(dto!=null){
            System.out.println(dto);
            Providorder providorder=new Providorder();
            providorder.setCode(dto.getOrderNumber());
            providorder.setName(dto.getSupplierName());
            providorder.setType(dto.getCommoditySort());
            providorder.setState("已发货");
            providorder.setAddress(dto.getCollectAddress());
            //时间格式转换
            DateTimeFormatter dtf =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            String format = dtf.format(LocalDateTime.now());
            providorder.setTime(format);

            providorder.setBatch(dto.getBatch());
            providorder.setSpecs(dto.getCommoditySize());
            providorder.setGoodsName(dto.getCommodityName());
            providorder.setNum(dto.getCommodityNum());
            providorder.setInPrice(dto.getCommodityPrice().floatValue());
            service.save(providorder);
            channel.basicAck(tag,false); //false不进行批量确认
        }
    }

    /**
     *这是一个消费者，采购计划的审核状态
     */
    @RabbitListener(queues = "PurchaseInfoQueue")
    public void ticket(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, PurchaseInfoDto dto) throws IOException {
        if(dto!=null){
            QueryWrapper qw=new QueryWrapper();
            qw.eq("code",dto.purchaseCode);
            BuyPlan buyPlan= buyPlanService.getOne(qw);
            buyPlan.setAuditState(dto.getPurchaseInfo());
            buyPlan.setNum(dto.getNum());
            buyPlanService.saveOrUpdate(buyPlan);


            channel.basicAck(tag,true); //false不进行批量确认
        }
    }

}
